package com.campus.controller;

import com.campus.constant.MessageConstant;
import com.campus.result.Result;
import com.campus.utils.AliyunOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/upload")
    public Result<String> upload(MultipartFile file) throws Exception {
        log.info("文件上传：{}", file.getOriginalFilename());

        try {
            //将文件交给阿里云OSS进行存储
            String url = aliyunOSSUtil.upload(file.getBytes(), file.getOriginalFilename());
            //返回文件url地址给前端
            return Result.success(url);
        } catch (Exception e) {
            log.error("文件上传失败：{}", e.getMessage());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
